package santeclair.referentiel.optique.tarification.webservice.impl;

import java.math.BigDecimal;
import java.util.List;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import santeclair.referentiel.optique.tarification.bean.detailTarif.DetailTarif;
import santeclair.referentiel.optique.tarification.dto.detailTarif.DemandeDetailTarifDto;
import santeclair.referentiel.optique.tarification.dto.detailTarif.DetailTarifDto;
import santeclair.referentiel.optique.tarification.dto.detailTarif.StatutTarifDto;
import santeclair.referentiel.optique.tarification.service.TarificationService;
import santeclair.referentiel.optique.tarification.webservice.DetailTarifWebService;
import santeclair.referentiel.optique.tarification.webservice.DetailTarifWrapper;

import com.google.common.base.Preconditions;

public class DetailTarifWebServiceImpl implements DetailTarifWebService {

    private static final Logger LOGGER = LoggerFactory.getLogger(DetailTarifWebServiceImpl.class);

    @Autowired
    private TarificationService tarificationService;

    @Override
    public DetailTarifDto getDetailTarifVerre(DemandeDetailTarifDto demandeDetailTarifDto) {

        Preconditions.checkNotNull(demandeDetailTarifDto, "Oject 'demandeDetailTarifDto' must not be null.");

        String codeVerre = demandeDetailTarifDto.getCodeVerre();
        Preconditions.checkNotNull(codeVerre, "Parameter codeVerre from 'demandeDetailTarifDto' must not be null");
        BigDecimal sphere = demandeDetailTarifDto.getSphere() != null ? demandeDetailTarifDto.getSphere() : new BigDecimal("0.00");
        BigDecimal cylindre = demandeDetailTarifDto.getCylindre() != null ? demandeDetailTarifDto.getCylindre() : new BigDecimal("0.00");
        Boolean domTom = demandeDetailTarifDto.getDomTom() != null ? demandeDetailTarifDto.getDomTom() : Boolean.FALSE;
        List<String> codeOpto10Supplements = demandeDetailTarifDto.getCodeOpto10Supplements();

        DetailTarifDto detailTarifDto = new DetailTarifDto();

        try {
            DetailTarif detailTarif = tarificationService.calculerTarif(codeVerre, sphere, cylindre, domTom, codeOpto10Supplements);
            detailTarifDto = DetailTarifWrapper.getDetailTarifDtoFromDetailTarif(detailTarif);

        } catch (Exception e) {
            String errorMessage = "Exception during 'getDetailTarifVerre' with contexte => \n\n " + demandeDetailTarifDto.toString() + "\n\n Exception : \n\n";
            LOGGER.error(errorMessage, e);
            detailTarifDto.setStatutDetailTarifDto(StatutTarifDto.ERROR);
            detailTarifDto.setMessage(errorMessage + ExceptionUtils.getStackTrace(e));
        }
        return detailTarifDto;
    }
}
